<template>
  <div class="app-container rtc-center">
    <div class="rtc-center-setting">
      <el-form inline>
        <el-form-item label="自动接听">
          <el-switch v-model="autoAnswer"/>
        </el-form-item>
        <el-form-item label="房间名">
          <el-input v-model="callStore.meetRecordName" placeholder="请输入房间名称"/>
        </el-form-item>
        <el-form-item label="分辨率">
          <el-select v-model="callStore.resolution">
            <el-option v-for="item in resolution" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="rtc-center-wrapper">
      <div class="rtc-info">
        <div class="rtc-device-search">
          <el-input v-model="filterStr" placeholder="请输入工号或姓名"/>
        </div>
        <div class="rtc-device-list">
          <el-scrollbar>
            <div v-for="device in deviceList" :key="device.userId" class="rtc-device-list-item">
              <div class="rtc-device-avatar">
                <img :src="device.avatar" alt=""/>
              </div>
              <div class="rtc-device-name">
                <span class="rtc-device-nickname" @click="moveMapCanter(device)"
                      :style="{'color': getIconColorByInclude([device.pcStatus, device.androidStatus, device.helmetStatus])}"
                >{{device.nickName}}</span>
                <span class="rtc-device-username">{{device.userName}}</span>
              </div>
              <div class="rtc-device-status">
                <div class="rtc-device-platform">
                  <el-icon :title="getPlatformTitle('安全帽端：', device.helmetStatus)" size="20"
                           :color="getIconColor(device.helmetStatus)"
                           @click="inviteAudio(device, deviceType.Helmet.value, device.helmetStatus)">
                    <Phone />
                  </el-icon>
                  <el-icon :title="getPlatformTitle('安全帽端：', device.helmetStatus)" size="20"
                           :color="getIconColor(device.helmetStatus)"
                           @click="invite(device, deviceType.Helmet.value, device.helmetStatus)">
                    <VideoCamera />
                  </el-icon>
                </div>
                <div class="rtc-device-battery">
                  <battery-level :percentage="device.batteryLevel"/>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="map-container" ref="mapContainer"/>
    </div>
  </div>
</template>

<script setup>
import {Monitor, Iphone} from "@element-plus/icons-vue";
import BatteryLevel from "@/components/BatteryLevel/index.vue";
import useCallStore from "@/store/modules/call";
import useUserStore from "@/store/modules/user";
import {deviceType} from "@/constant/deviceType";
import {deviceStatus} from "@/constant/deviceStatus";
import {resolution} from "@/constant/resolution";
import defaultAvatar from "@/assets/images/profile.jpg"
import {computed, getCurrentInstance, markRaw, onMounted, ref, watch} from "vue";
import EventBus from "@/utils/eventBus";
import {key, keyCode} from "@/constant/amap";
import AMapLoader from "@amap/amap-jsapi-loader";
import {callType} from "@/constant/callType";

const {proxy: currentInstance} = getCurrentInstance()

const userStore = useUserStore()
const callStore = useCallStore()

const autoAnswer = ref(false)
const filterStr = ref('')
let map = null
let markerLayers = null
let helmetMarkerMap = markRaw({})

const deviceList = computed(() => {
  const rtcDeviceMap = callStore.rtcDeviceMap
  if (Object.values(rtcDeviceMap).length === 0) {
    return []
  }
  const devices = []
  for (const key in rtcDeviceMap) {
    if (Number(key) === userStore.userId) {
      continue
    }

    const list = rtcDeviceMap[key]
    let data = {}
    for (const item of list) {
      if (item.deviceType === deviceType.PC.value) {
        data.pcStatus = item.status
      } else if (item.deviceType === deviceType.Android.value) {
        data.androidStatus = item.status
      } else if (item.deviceType === deviceType.Helmet.value) {
        data = {
          ...data,
          ...item,
          helmetStatus: item.status
        }
      }
    }

    data.batteryLevel = data.batteryLevel ? data.batteryLevel : 0
    if (data.avatar === '' || data.avatar === null || data.avatar === undefined) {
      data.avatar = defaultAvatar
    }
    let statusArr = [data.pcStatus, data.androidStatus, data.helmetStatus]
    let totalStatus = statusArr.indexOf(deviceStatus.Online.value) !== -1
    data.totalStatus = totalStatus ? 1 : 0
    devices.push(data)
  }

  devices.sort((a,b) => b.totalStatus - a.totalStatus)
  if (filterStr.value !== '') {
    return devices.filter(device => device.userName.includes(filterStr.value) || device.nickName.includes(filterStr.value))
  }
  console.log('devices', devices);
  return devices
})

watch(deviceList, () => {
  loadLabelMarker()
})

onMounted(() => {
  initMap()
})

function getPlatformTitle(prefix, status) {
  return `${prefix}${status === deviceStatus.Online.value ? '在线' : '离线'}`
}

function getIconColor(status) {
  return status === deviceStatus.Online.value ? 'var(--el-color-primary)' : 'var(--el-text-color-disabled)'
}

function getIconColorByInclude(statusArr) {
  return statusArr.indexOf(deviceStatus.Online.value) !== -1 ? 'var(--el-color-primary)' : 'var(--el-text-color-disabled)'
}

function invite(device, type, status) {
  console.log('音视频, device', device)
  if (status === deviceStatus.Offline.value) {
    return
  }

  const data = {
    ...device,
    deviceType: type,
    callType: callType.Both.value
  }
  console.log('音视频, data', data)
  EventBus.emit('invite', data)
}

function inviteAudio(device, type, status) {
  console.log("音频，device:", device);
  if (status === deviceStatus.Offline.value) {
    return
  }
  const data = {
    ...device,
    deviceType: type,
    callType: callType.Audio.value
  }
  console.log('音频, data', data)
  EventBus.emit('invite', data)
}

async function initMap() {
  if (!window.AMap) {
    window._AMapSecurityConfig = {
      securityJsCode: keyCode
    }
    try {
      await AMapLoader.load({
        key,
        version: '2.0',
        plugins: ['AMap.MouseTool', 'AMap.ContextMenu', 'AMap.PolyEditor', 'AMap.MapType', 'AMap.Scale', 'AMap.OverView',
          'AMap.ControlBar', 'Map3D', 'AMap.DistrictSearch', 'AMap.MarkerClusterer', 'AMap.ToolBar', 'AMap.Geolocation',
          'AMap.MoveAnimation']
      })
    } catch (e) {
      currentInstance.$modal.msgError('地图加载失败')
    }
  }

  map = markRaw(new AMap.Map(currentInstance.$refs.mapContainer, {
    resizeEnable: true,
    rotateEnable: true,
    pitchEnable: true,
    showLabel: true,
    zoom: 16,
    zooms: [2, 30],
    rotation: 0,
    viewMode: '3D',
    skyColor: '#132237',
  }))
  const geoLocation = new AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0,
    convert: true,
    showButton: true,
    position: 'RB',
    offset: [20, 90],
    showMarker: true,
    showCircle: true,
    panToLocation: true,
    zoomToAccuracy: true
  })
  map.addControl(geoLocation)
  geoLocation.getCurrentPosition(() => {})
  map.addControl(new AMap.ToolBar())
  map.addControl(new AMap.ControlBar())
  map.addControl(new AMap.Scale())
  map.addControl(new AMap.MapType({defaultType:1}))

  markerLayers = markRaw(new AMap.LabelsLayer({
    collision: true,
  }))
  map.add(markerLayers)

  loadLabelMarker()
}

function loadLabelMarker() {
  if (map === null) {
    return
  }

  for (const device of deviceList.value) {
    const {userId, nickName, latitude, longitude, avatar, helmetStatus} = device

    if (helmetStatus === deviceStatus.Offline.value) {
      const labelMarker = helmetMarkerMap[userId]
      if (labelMarker) {
        markerLayers.remove(labelMarker)
      }
      delete helmetMarkerMap[userId]
      continue
    }

    if (latitude === null || longitude === null) {
      continue
    }

    const labelMarker = helmetMarkerMap[userId]
    if (labelMarker) {
      labelMarker.moveTo([longitude, latitude])
    } else {
      const marker = new AMap.LabelMarker({
        position: [longitude, latitude],
        icon: {
          image: avatar === '' ? defaultAvatar : avatar,
          size: [48, 48],
          anchor: 'center'
        },
        text: {
          content: nickName,
          offset: [0, 70],
          style: {
            backgroundColor: '#eee',
            borderColor: '#333',
            borderWidth: 1
          }
        }
      })

      helmetMarkerMap[userId] = marker

      markerLayers.add(marker)
    }
  }
}

function moveMapCanter(device) {
  const {userId,latitude, longitude} = device;

  if (latitude === null || longitude === null) {
    currentInstance.$modal.msg('未获取到该安全帽的位置信息，可能该安全帽从未上传过位置信息')
    return
  }

  map.panTo([longitude, latitude])
}
</script>

<style scoped lang="scss">
.rtc-center {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .rtc-center-wrapper {
    flex: 1;
    width: 100%;
    display: flex;
    overflow: hidden;

    .rtc-info {
      width: 25%;
      height: 100%;
      border: 1px solid #DCDFE6;
      border-radius: 1px;
      display: flex;
      flex-direction: column;
      padding: 10px;
      box-sizing: border-box;

      .rtc-device-search {
        padding-bottom: 10px;
      }

      .rtc-device-list {
        flex: 1;
        overflow: hidden;
        box-sizing: border-box;
        border: 1px solid #DCDFE6;
        border-radius: var(--el-border-radius-base);

        .rtc-device-list-item {
          box-sizing: border-box;
          display: flex;
          height: 52px;
          padding: 5px 10px 5px 5px;
          transition: background ease-in-out 200ms;
          &:not(:last-child) {
            border-bottom: 1px solid #DCDFE6;
          }
          &:hover {
            background: var(--el-color-primary-light-9);
          }

          .rtc-device-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .rtc-device-name {
            padding-left: 5px;
            height: 100%;
            flex: 1;

            .rtc-device-nickname, .rtc-device-username {
              height: 50%;
              display: flex;
              align-items: center;
            }

            .rtc-device-username {
              font-size: 14px;
              color: #aaa;
            }

            .rtc-device-nickname {
              font-weight: bold;
              //color: var(--el-color-primary);
              cursor: pointer;
            }
          }

          .rtc-device-status {
            height: 100%;

            .rtc-device-platform {
              .el-icon {
                margin-left: 3px;
                cursor: pointer;
              }
            }

            .rtc-device-battery {
              width: 100%;
              height: 50%;
            }
          }
        }
      }
    }

    .map-container {
      flex: 1;
      height: 100%;
    }
  }
}
</style>
